#include <sstream>

#include "smsio.hpp"
#include "sys_var.hpp"
#include "at.hpp"
/*
int QL_SMS_GetSmsCenterAddress( sms_client_handle_type     h_sms,
                       ql_sms_service_center_cfg_t *set_sca_cfg);

// Set sms center address.

int QL_SMS_SetSmsCenterAddress( sms_client_handle_type     h_sms,
                       ql_sms_service_center_cfg_t *get_sca_cfg);
*/
smsio::smsio( io_type ht , filterList* l ):
	filterIO( ht , l )
{
	try{
		ptSMS = std::move( std::unique_ptr<sms>( new sms()));
		if( ptSMS ){
			init_events();
		}
	}catch(std::bad_alloc& e ){
		std::cout << "" << std::endl;
		abort();
	}
	std::shared_ptr< CSysVar > ptvar = GetOrCreateSysVar();
	if( ptvar ){
		bool en;
		ptvar->GetValue( "/sms/enable" , en );
		m_enable = en;
	}else{
		m_enable = false;
	}
}

smsio::~smsio()
{

}

void smsio :: init_events()
{
	ptSMS->OnMsg([this](const std::string& from , const char * d , size_t l , sms::sms_type type ){
#if defined( __DEBUG__ )
		std::cout << __FILE__ << " Recv msg from :" << from << std::endl;
#endif
		m_from = from;
		OnRecv( l , d , OK );
	});

	ptSMS->OnSend( [ this ]( sms::err_code e ){

	});

	ptSMS->OnOpen([ this ]( ){ //

	});

	ptSMS->OnClose([ this ]{

	});
}

bool smsio::on_forward( size_t len , const char * data , err_code &err , size_t& rlen , char ** rd )
{
	if( IsInSerialAT() ){
		*rd = ( char *)data;
		rlen = len;
		return false;
	}
#if defined( __DEBUG__ )
	std::cout << "SMS Forward called." << std::endl;
#endif
	bool flag = false;
	for( size_t i = 0; i < len; i ++ ){
		if( data[ i ] > 0x80 ) flag = true;
	}
	if( flag ){ // 按 UCS2 格式发送短信，虽然这个判断并不完全正确。但是按照超时可以显示字符来判断
		// 是否包含了汉字还是可以用的
		ptSMS->send( m_from , len , data , sms::UCS2 );
	}else{ // 赞找 GSM7 发送短信
		ptSMS->send( m_from , len , data , sms::GSM_7BIT );
	}

	*rd = ( char *)data;
	rlen = len;
	return false;
}

bool smsio::on_backward( size_t len , const char * data , err_code &err , size_t& rlen , char ** rd  )
{
	if( IsInSerialAT() ){
		*rd = ( char *)data;
		rlen = len;
		return false;
	}
#if defined( __DEBUG__ )
	std::cout << __FILE__ << " [ " << __LINE__ << " ] Recv SMS:" << data << std::endl;
#endif
	*rd = ( char *)data;
	rlen = len;
	return true;
}
